//
//  SEGVisitorAccessManager.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/5/11.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGVisitorAccessManager.h"
#import "SEGVisitorAccessCodeModel.h"
#import "SEGVisitorAccessHistoryModel.h"

@implementation SEGVisitorAccessManager

+ (instancetype)shareManager {
    static SEGVisitorAccessManager* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

/**
 * 请求通行次数
 * @author Wendy
 * @param finished 回调结果
 */
- (void)requestAccessNumber:(SEGNetworkReponse)finished
{
    [[SEGFindDictionaryInfoManagr sharedManager] requestDictionaryInfoByCode:@"TEMPORARY_PASS" completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 * 请求访客登记接口
 * @author Wendy
 * @param dict 信息字典
 * @param finished 回调结果
 */
- (void)requestSaveVisitCustomListWithDict:(NSDictionary *)dict finished:(SEGNetworkReponse)finished
{
    // 4.9.6 转换json不能使用NSJSONWritingPrettyPrinted，这个参数转换的json会带空格或制表符，导致接口被阿里防火墙拦截
    NSString *dictString;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
    if (!jsonData) {
        dictString = @"";
    }
    dictString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:dictString, @"vistCustsInfo", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kUhomecp_admin,@"/rest-api/v4/adminuser/saveVistCustList",nil];
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        NSString* code = codeType;
        NSString* message = errorMessage;
        
        if (isSuccessed) {
            if (![[result valueForKey:@"data"] isKindOfClass:[NSArray class]]) {
                finished(NO, result, @"-1", kNetworkErrorMessage);
                return;
            }
            self.codeModel = [SEGVisitorAccessCodeModel yy_modelWithDictionary:result[@"data"][0]];
            finished(YES, result, code, message);
        } else {
            finished(isSuccessed, result, codeType, errorMessage);
        }
        
    }];
}

/**
 * 请求访客来访历史记录接口
 * @author Wendy
 * @param pageNo 页码
 * @param pageLength 每页数据条数
 * @param finished 回调结果
 */
- (void)requestVisitHistoryListWithPageNo:(NSUInteger)pageNo pageLength:(NSUInteger)pageLength finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = @{
                            @"userId" : kAccountUserID,
                            @"organId" : kAccountCommunityID,
                            @"pageNo" : [NSString stringWithFormat:@"%lu",(unsigned long)pageNo],
                            @"pageLength" : [NSString stringWithFormat:@"%lu",(unsigned long)pageLength]
                            };
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kUhomecp_admin,@"/rest-api/v4/adminuser/getVistCustLogByXCSH",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(isSuccessed, result, codeType, errorMessage);
            return;
        }
        
        NSDictionary *dataDict = [result valueForKey:@"data"];
        NSArray *arr = dataDict[@"result"];
        if (pageNo != 1 && arr.count == 0) {
            finished(NO, result, codeType, @"没有更多数据了！");
            return;
        }
        
        if (arr && [arr isKindOfClass:[NSArray class]]) {
            //刷新时 清空之前的数据
            if(pageNo == 1) {
                [self.historyArray removeAllObjects];
            }
            
            [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[NSDictionary class]]) {
                    SEGVisitorAccessHistoryModel *histroyModel = [SEGVisitorAccessHistoryModel initWithDictionary:obj];
                    [self.historyArray addObject:histroyModel];
                }
            }];
        }
        self.pageNo = [dataDict[@"pageNo"] integerValue];
        self.pageLength = [dataDict[@"pageLength"] integerValue];
        self.totalPage = [dataDict[@"totalPage"] integerValue];
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 * 请求分享通行证接口
 * @author Wendy
 * @param finished 回调结果
 */
- (void)requestShareVisitorPassportWithVistLogid:(NSString *)vistLogid finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:vistLogid, @"vistLogid", kAccountCommunityID,@"organId", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kUhomecp_admin,@"/rest-api/v4/adminuser/shareVistCustPassPort",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            self.codeModel = [SEGVisitorAccessCodeModel yy_modelWithDictionary:result[@"data"][0]];
        }
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

- (NSMutableArray<SEGVisitorAccessHistoryModel *> *)historyArray {
    if (!_historyArray) {
        _historyArray = [NSMutableArray array];
    }
    return _historyArray;
}

@end
